﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InductBase;
using SharpBolt.Graphics.GraphicInstances;
using SharpBolt.Sound;

namespace SharpBolt.Complex
{
    public class CustomSpriteInstance
    {
        public CustomSpriteSource Source;
        public CustomSpriteSource.Frame CurrentFrame;

        public Transformation Transformation
        {
            get
            {
                if (spriteInstance == null) return Transformation.Default;
                return spriteInstance.Transformation;
            }

            private set
            {

            }
        }

        SpriteInstance spriteInstance;

        public void Attach(SpriteInstance spriteInstance)
        {
            if (spriteInstance != null)
            {
                if(this.spriteInstance!=null)
                this.spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);    
              
                spriteInstance.FrameChanged += new EventHandler(spriteInstance_FrameChanged);
            }

            this.spriteInstance = spriteInstance;            
        }

        public void Detach(SpriteInstance spriteInstance = null)
        {
            if (spriteInstance == null)
            {
                this.spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);
            }
            else
            {
                spriteInstance.FrameChanged -= new EventHandler(spriteInstance_FrameChanged);
            }
        }

        void spriteInstance_FrameChanged(object sender, EventArgs e)
        {
            CurrentFrame = 
                Source.
                Sequences[spriteInstance.CurrentSequenceIndex].
                Frames[spriteInstance.CurrentFrameIndex];

            if (CurrentFrame.Sound != "")
            {
                string effectName = CurrentFrame.Sound.Remove(0,
                    CurrentFrame.Sound.LastIndexOf(Engine.ResourcesPrefix) + Engine.ResourcesPrefix.Length);
                var sfxplayer = new SfxPlayer();
                sfxplayer.LoadSoundEffect(effectName);
                sfxplayer.Volume = this.SoundVolume;
                sfxplayer.Play();
            }            
        }

        public CustomSpriteInstance(CustomSpriteSource source)
        {
            Source = source;
            SoundVolume = .25;            
        }

        public double SoundVolume;        
    }
}
